
//
//  CYBuyViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/6/9.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYBuyViewController.h"
#import "CYTrendViewController.h"
#import "CYMyNoticeViewController.h"
#import "CYDataSourceDelegate.h"
#import "CYHomePageCell.h"
#import "CYHeaderCRView.h"
#import "CYRegisterViewController.h"
#import "CYBettingViewController.h"
#import "CYHomeModel.h"
#import "CYWebViewController.h"
@interface CYBuyViewController ()<CYScrollDelegate>{
    CYCollectionDelegate *_delegate;
    CYCollectionDataSource *_datasource;
}
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSDictionary *data;//数据源
@property (nonatomic, copy) NSMutableArray *dataArr;//转换成数组的数据源
@property (nonatomic, assign) BOOL isLogin;//是否登录
@property (nonatomic, strong) NSIndexPath *refreshIndexpath;//仅仅刷新当前的cell
@property (nonatomic, strong) CYHomeModel *model;
@end

@implementation CYBuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

/*懒加载*/
- (UICollectionView *)collection{
    if (!_collection) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 0.0;
        layout.minimumInteritemSpacing = 0.0;
        _collection = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collection.showsVerticalScrollIndicator = NO;
        _collection.mj_header = [CYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDown)];//下拉刷新
        [self.view addSubview:_collection];
        [self setupCollection];
        
        [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(STATUS_HEIGHT, 0.0, TABBAR_HEIGHT, 0.0));
        }];
    }
    return _collection;
}

- (void)setData:(NSDictionary *)data{
    if (!data)
        _data = [CYCache getCache:@"Lottery.plist"];
    else if (_data != data){
        _data = data;
        [CYCache cache:_data plist:@"Lottery.plist"];
    }
    self.dataArr = [self convertToArray:_data];
    
}

- (void)setDataArr:(NSMutableArray *)dataArr{
    if (!dataArr)
        return;
    if (_dataArr != dataArr)
        _dataArr = dataArr;
    if (!_collection)
        self.collection.backgroundColor = [UIColor whiteColor];
    _datasource.dataArr = _dataArr;
    _collection.contentOffset = CGPointZero;
    if (_refreshIndexpath)
        [UIView performWithoutAnimation:^{
            [_collection reloadItemsAtIndexPaths:@[_refreshIndexpath]];
        }];
    else
        [UIView performWithoutAnimation:^{
            [_collection reloadData];
        }];
    
}

/*设置collection*/
- (void)setupCollection{
    
    /*注册cell，headerview,footerview*/
    [_collection registerClass:[CYHomePageCell class] forCellWithReuseIdentifier:@"CYHomePageCell"];
    //    [_collection registerClass:[CYCycleCell class] forCellWithReuseIdentifier:@"CYCycleCell"];
    [_collection registerClass:[CYHeaderCRView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [_collection registerClass:[CYFooterCRView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
    WS(self)
    _datasource = [[CYCollectionDataSource alloc]initWithData:_dataArr identifier:@"CYHomePageCell" views:nil block:^(id cell, id data, id index) {
        [weakSelf bindCell:cell data:data index:index];
    }];
    
    //    _datasource = [[CYCollectionDataSource alloc]initWithData:nil identifierArr:@[@"CYCycleCell", @"CYHomePageCell"] views:nil block:^(id cell, id data, id index) {
    //        [weakSelf bindCell:cell data:data index:index];
    //    }];
    _delegate = [[CYCollectionDelegate alloc]initWithData:nil block:^(NSIndexPath *index) {
        [weakSelf selectCell:index];
    }];
    /*设置collection代理*/
    _collection.dataSource = _datasource;
    _collection.delegate = _delegate;
    _delegate.delegate = self;
}

/*绑定数据*/
- (void)bindCell:(id)cell data:(NSDictionary *)dict index:(NSIndexPath *)index{
    CYHomePageCell *newcell = (CYHomePageCell *)cell;
    /*判断是不是最后两行row，如果是，cell隐藏下划线*/
    NSUInteger count = [_dataArr[index.section] count];
    if (count % 2 == 0)//如果是双数，则最后两个cell隐藏下划线
        newcell.isLastRow = (index.row == (count - 1) || index.row == (count - 2))?YES:NO;
    else//否则，最后一个隐藏下划线
        newcell.isLastRow = (index.row == (count - 1))?YES:NO;
    newcell.name = dict[@"name"];
    newcell.time = dict[@"endTime"];
    [CYHttps loadingWithFile:dict[@"img"] complete:^(id data) {//从URL加载图片
        newcell.image = data;
    }];
    WS(self)
    newcell.refreshBlock = ^{//完成倒计时,重新请求数据,自动刷新
        weakSelf.refreshIndexpath = index;
        [weakSelf httpsHome];
    };
}

/*选中cell*/
- (void)selectCell:(NSIndexPath *)index{
    CYBettingViewController *bettingVC = [[CYBettingViewController alloc]init];
    bettingVC.lottery_name = _dataArr[index.section][index.row][@"name"];//
    bettingVC.lottery_id = _dataArr[index.section][index.row][@"id"];
    [self.navigationController pushViewController:bettingVC animated:YES];
}

- (void)abcd:(UIButton *)sender{
    if (sender.tag - 200 == 0) {
        [self performSelector:@selector(login:) withObject:self.navigationItem.leftBarButtonItem];
    }
    else if (sender.tag - 200 == 1) {
        CYMyNoticeViewController *noticeVC = [[CYMyNoticeViewController alloc]init];
        noticeVC.previousVCName = @"CYBuyViewController";
        [self.navigationController pushViewController:noticeVC animated:YES];
    }
    else if (sender.tag  - 200 == 2 ) {
        
        CYTrendViewController *trendVC = [[CYTrendViewController alloc]init];
        trendVC.lottery_name = _data[@"high"][0][@"name"];
        trendVC.lottery_id = _data[@"high"][0][@"id"];
        trendVC.previousVC = @"CYBuyViewController";
        [self.navigationController pushViewController:trendVC animated:YES];
    }else{//客服
        if (![CYUser shareUser].token || ![CYUser shareUser].token){
            Class VC = NSClassFromString(@"CYFreeTrialViewController");
            [self.navigationController pushViewController:[VC new] animated:YES];
        }
        else{
            CYWebViewController *webVC = [[CYWebViewController alloc]init];
            webVC.title = @"客服";
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }
    
}

//登录
- (void)login:(UIBarButtonItem *)sender{
    if (![CYUser shareUser].token || ![CYUser shareUser].token){//如果未登录，点击登录按钮，进入登录界面
        Class VC = NSClassFromString(@"CYLoginViewController");
        [self.navigationController pushViewController:[VC new] animated:YES];
    }
    else{
        UITabBarController *tabVC  =  (UITabBarController *)[[[UIApplication sharedApplication] keyWindow] rootViewController];
        tabVC.selectedIndex = 3;
    }
}

//注册
- (void)registerUser:(UIBarButtonItem *)sender{
    CYRegisterViewController *registerVC = [[CYRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
    
}

//下拉刷新
- (void)refreshDown{
    _refreshIndexpath = nil;//置空刷新某一行的indexpath
    [self httpsHome];
}

//导航栏显示与颜色
- (void)setupNavigationBarAlpha:(CGFloat)alpha hidden:(BOOL)hidden{
    alpha = (alpha > 0.9)?1:alpha;//强制alpha等于1
    self.navigationController.navigationBar.hidden = hidden;
    if (hidden == NO)
        [self.navigationController.navigationBar setBarTintColor:[THEME_COLOR colorWithAlphaComponent:alpha]]; //设置导航栏背景颜色
    
}

#pragma mark - UICollectionViewDelegate.delegate
- (void)scrollDelegate:(UIScrollView * )scrollView{
    if (_isLogin)
        return;
    if (scrollView.contentOffset.y <= AL(PT(378 / 750.0 * SCREEN_WIDTH)) && scrollView.contentOffset.y >= 0){
        CGFloat alpha = scrollView.contentOffset.y / AL(PT(378 / 750.0 * SCREEN_WIDTH));
        [self setupNavigationBarAlpha:alpha hidden:NO];//固定的区域滑动
    }
    else if (scrollView.contentOffset.y > AL(PT(378 / 750.0 * SCREEN_WIDTH))){
        //        [self setupNavigationBarAlpha:(CGFloat)fabsf(alpha - floorf(alpha)) hidden:NO];//超出固定的区域滑
    }
    
}

//判断是否登录
- (BOOL)judgeIsLogin{
    if ([CYUser shareUser].token){
        self.navigationController.navigationBar.hidden = YES;
        return YES;
    }
    else {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(login:)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registerUser:)];
        return NO;
    }
}

//如果缓存中没有数据，则模拟一组数据
- (NSMutableArray *)getDataArr{
    
    NSDictionary *dict = [CYCache getCache:@"Lottery.plist"];
    
    NSMutableArray *array = [self convertToArray:dict];
    if (array && array.count > 0)
        return array;
    NSArray *subArr_first = @[ @{@"name":@"重庆时时彩",@"img":@"cqssc",@"endTime":@""},
                               @{@"name":@"广东11选5",@"img":@"gd11x5",@"endTime":@""},
                               @{@"name":@"山东11选5",@"img":@"sd11x5",@"endTime":@""},
                               @{@"name":@"上海时时乐",@"img":@"shssl",@"endTime":@""},
                               @{@"name":@"新疆时时彩",@"img":@"xjssc",@"endTime":@""},
                               @{@"name":@"江西11选5",@"img":@"jx11x5",@"endTime":@""},
                               @{@"name":@"北京PK拾",@"img":@"bjpks",@"endTime":@""},
                               @{@"name":@"上海11选5",@"img":@"sh11x5",@"endTime":@""},
                               @{@"name":@"江苏快三",@"img":@"jsks",@"endTime":@""},
                               @{@"name":@"天津时时彩",@"img":@"tjssc",@"endTime":@""},
                               @{@"name":@"安徽快三",@"img":@"ahks",@"endTime":@""},
                               @{@"name":@"广西快三",@"img":@"gxks",@"endTime":@""}];
    
    NSArray *subArr_second = @[ @{@"name":@"福彩3D",@"img":@"fc3d",@"endTime":@""},
                                @{@"name":@"排列三",@"img":@"pls",@"endTime":@""}];
    return [NSMutableArray arrayWithObjects:subArr_first, subArr_second, nil];
}

//数据源转换成数组
- (NSMutableArray *)convertToArray:(NSDictionary *)dict{
    if (dict == nil || [dict count] < 1)
        return nil;
    NSMutableArray *array = [NSMutableArray array];
    //    if ([dict[@"lunbo"] count] > 0)
    //        [array addObject:dict[@"lunbo"]];
    if ([dict[@"high"] count] > 0)
        [array addObject:dict[@"high"]];
    if ([dict[@"low"] count] > 0)
        [array addObject:dict[@"low"]];
    return array;
}

//首页请求网络
- (void)httpsHome{
    if (!_collection)
        self.data = nil;
    BOOL show = (_refreshIndexpath)?NO:YES;
    self.task = [CYHttps GET:API_index parameters:nil showHUD:(show) progress:nil success:^(id data) {
        if (_collection)
            [_collection.mj_header endRefreshing];
        self.data = data;
    }failure:^(id string) {
        if (_collection)
            [_collection.mj_header endRefreshing];
    }];
    
}

//获取所有彩种的简单信息
-  (void)httpsAllLottery{
    
    self.spareTask = [CYHttps POST:API_possess parameters:nil showHUD:NO progress:nil success:^(id data) {
        if (data)
            [CYCache cache:data plist:@"LotteryName.plist"];
    } failure:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupNavigationBarTintColor:[UIColor clearColor]];
    _isLogin = [self judgeIsLogin];//判断是否登录
    //    if (_collection)
    //        [self performSelector:@selector(scrollDelegate:) withObject:_collection];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //    _isLogin = [self judgeIsLogin];//判断是否登录
    //    if (_collection)
    //        [self performSelector:@selector(scrollDelegate:) withObject:_collection];
    [self httpsHome];//请求首页
    [self httpsAllLottery];//请求所有彩种
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
